package com.eystar.pdc.model;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.SqlPara;

import cn.hutool.core.util.StrUtil;
/**
 * 机构Model
 * @author Your_Name
 *
 */
@TableBind(tableName = "t_pdc_org")
public class Org extends ModelExt<Org> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static Org dao = new Org();
	
	/**
	 * 列出机构树形结构，以JSON格式返回
	 * 
	 * @return
	 */
	public JSONArray listOrgJson(Org org){
		List<Org> orgs = find(getSqlPara("pdc.org.listOrgJson", org));
		JSONArray array = new JSONArray();
		for (Org org2 : orgs) {
			JSONObject object = JSONObject.parseObject(org2.toJson());
			if (StrUtil.isNotBlank(org.getStr("org_name"))) { // 说明正在查询，直接封装，不用调用属性结果
				array.add(object);
				continue;
			}
			if (StrUtil.equals("0", org2.getStr("org_pid"))) { // 父节点
				object.put("text", org2.getStr("org_name"));
				constructJson(orgs, org2.getStr("id"), object);
				array.add(object);
			}
		}
		return array;
	}
	
	/**
	 * 递推循环，json形式
	 * 
	 * @param orgs
	 * @param parentId
	 * @param object
	 */
	private void constructJson(List<Org> orgs, String parentId, JSONObject object) {
		JSONArray array = new JSONArray();
		for (Org org : orgs) {
			if (parentId.equals(org.getStr("org_pid"))) {
				JSONObject child = JSONObject.parseObject(org.toJson());
				child.put("text", org.getStr("org_name"));
				constructJson(orgs, org.getStr("id"), child);
				array.add(child);
			}
		}
		if (array != null && array.size() > 0) {
			object.put("children", array);
		}
	}
	
	public Org findOrgById(String id){
		Kv kv = Kv.by("id", id);
		SqlPara sqlPara = getSqlPara("pdc.org.findOrgById",kv);
		return findFirst(sqlPara);
	}
}